package com.cuanbobox.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取安卓权限工具类
 */
public class Permission {
    private List<String> permissionList = new ArrayList<>();
    private static Permission p;

    private Permission() {

    }

    public static Permission getInstance() {
        p = new Permission();
        return p;
    }

    /**
     * 添加需要请求的权限
     */
    public Permission add(String permission) {
        permissionList.add(permission);
        return p;
    }

    /**
     * 获取权限
     *
     * @param aty Activity对象
     */
    public void request(Activity aty) {
        List<String> needRequestPermission = new ArrayList<>();
        for (int i = 0; i < permissionList.size(); i++) {
            if (permissionList.get(i).equals(Manifest.permission.SYSTEM_ALERT_WINDOW)) {//当要获取悬浮窗权限时
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!Settings.canDrawOverlays(aty)) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                                Uri.parse("package:" + aty.getPackageName()));
                        aty.startActivityForResult(intent, 10);
                    }
                }
            } else if (ContextCompat.checkSelfPermission(aty, permissionList.get(i)) != PackageManager.PERMISSION_GRANTED) {// 没有权限
                needRequestPermission.add(permissionList.get(i));
            }
        }
        if (needRequestPermission.size() > 0) {
            String[] permissionAry = new String[needRequestPermission.size()];
            for (int i = 0; i < needRequestPermission.size(); i++) {
                String s = needRequestPermission.get(i);
                permissionAry[i] = s;
            }
            ActivityCompat.requestPermissions(aty, permissionAry, 1001);
        }
        permissionList.removeAll(permissionList);
    }

    /**
     * 如果有权限没有获取到，那么就会弹出Toast提示
     *
     * @param permissions  权限的数组集合
     * @param grantResults 获取结果
     */
    public void noPermissionPrompt(Context context, String[] permissions, int[] grantResults) {
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {// 没有权限
                Toast.makeText(context, "未获取到权限:" + permissions[i], Toast.LENGTH_LONG).show();
            }
        }
    }
}
